<template>
  <view class="home-page" :style="{ height: homePageHeight }">
    <start-page
      v-if="!innitStartPage && showStartPage"
      :countDownTime="appConfig.countDownTime"
      :isMember="appConfig.isMember"
      :businessName="appConfig.businessName"
      :businessLogo="appConfig.businessLogo"
      :splashScreen="appConfig.splashScreen"
    />
    <address-bar ref="addressBarRef" @handleSearch="handleSearch" />
    <low-code-page
      ref="lcpRef"
      hideNavbar
      v-if="pageData"
      :pageJson="pageData"
      :navBarHeight="navBarHeight"
    />
    <modal
      content="定位权限未开启，请点击【去设置】并手动允许，或进行手动定位"
      @confirm="handleOpenSetting"
      @cancel="handleOpenLocation"
      :show-title="false"
      leftBtnText="手动定位"
      rightBtnText="去设置"
      :visible.sync="modalVisible"
    />
    <cus-tab-bar ref="cusBarRef" />
  </view>
</template>

<script>
import { TENCENT_MAP_KEY } from "@/const/address/key";
import { mapState } from "vuex";
import { getPageJson } from "@/service/api/sp-common/widget";
import CusTabBar from "@/components/baseComponents/yqd-cus-tabbar";
import store from "@/store";
import { getWxConfig } from "@/service/api/sp-common/config";
import { getUrlQuery } from "@/utils/format";
import { appRemoveStorage } from "@/utils/storage";
import { TABLE_QUERY_KEY } from "@/pages/sp-store/const";
import startPage from "@/components/pageComponents/home/startPage";
import addressBar from "@/components/pageComponents/home/address-bar";

export default {
  components: { addressBar, CusTabBar, startPage },
  data() {
    return {
      //启动页
      showStartPage: false,
      //启动页结束
      loading: false,
      modalVisible: false,
      pageData: null,
      options: null,
      homePageHeight: "100vh",
      navBarHeight: 0,
      cusBarHeightForPx: 0,
    };
  },
  computed: {
    ...mapState("sp-address/location", ["currentLocation"]),
    ...mapState("sp-common/user", ["location"]),
    ...mapState("sp-common/base", ["appConfig", "innitStartPage"]),
  },
  watch: {
    // currentLocation: {
    //   handler(val) {
    //     // //console.log("更新currentLocation", val);
    //     if (val?.latitude > 0) {
    //       uni.$u.throttle(this.handleGetNearbyLocation, 500);
    //     }
    //   },
    //   deep: true,
    //   immediate: true,
    // },
    // location: {
    //   handler(val) {
    //     // //console.log("更新location", val);
    //     if (val?.latitude > 0) {
    //       uni.$u.throttle(this.handleGetNearbyLocation, 500);
    //     }
    //   },
    //   deep: true,
    //   immediate: true,
    // },
    loading(val) {
      if (val) {
        uni.showLoading({ title: "加载中" });
      } else {
        uni.hideLoading();
      }
    },
  },
  onShow() {
    this.initLocation();
  },
  created() {
    this.loading = true;
    // this.$store.dispatch("sp-common/base/getUserWxConfig");
  },
  onLoad(options) {
    console.log("home-onLoad");
    this.options = options;
    this.init();
    // this.initLocation();
    this.navBarHeight = this.$refs.addressBarRef.height;
    if (options?.pageId) {
      this.$nextTick(() => {
        this.initLowCodePage();
      });
    }
    appRemoveStorage(TABLE_QUERY_KEY);
  },
  methods: {
    async init() {
      if (!this.$Route?.query?.pageId) {
        console.log("执行初始化低代码参数");
        const res = await getWxConfig();
        const { tabBarList } = res;
        tabBarList.map((v) => {
          const openInsideParams = JSON.parse(v.openInsideParams);
          if (openInsideParams.commonCode === "PUB_HOME_PAGE") {
            const query = getUrlQuery(v.openPath);
            this.options.pageId = query.pageId;
            this.$nextTick(() => {
              this.initLowCodePage();
            });
          }
        });
      }
    },
    initLocation() {
      uni.authorize({
        scope: "scope.userLocation",
        success: () => {
          uni.getLocation({
            isHighAccuracy: true,
            type: "gcj02",
            success: (res) => {
              this.modalVisible = false;
              store?.dispatch("sp-common/user/setUserLocation", res);
              //无手动定位的时候才刷新手动定位
              if (!this.currentLocation) {
                store?.dispatch("sp-address/location/setCurrentLocation", res);
                this.$nextTick(() => {
                  this.handleGetNearbyLocation();
                });
              }
            },
            fail: () => {
              this.checkModalVisible();
              this.$nextTick(() => {
                this.handleGetNearbyLocation();
              });
            },
          });
        },
        fail: () => {
          this.checkModalVisible();
          this.$nextTick(() => {
            this.handleGetNearbyLocation();
          });
        },
      });
    },
    initLowCodePage() {
      const { pageId } = this.options;
      // //console.log("加载低代码", pageId);
      if (pageId) {
        getPageJson({ id: pageId }).then((res) => {
          if (res) {
            this.handleGetCusBarHeight();
            this.pageData = JSON.parse(res.pageJson);
            this.loading = false;
          }
        });
      }
    },
    checkModalVisible() {
      if (!this.currentLocation) {
        return (this.modalVisible = true);
      }
      const { latitude, longitude } = this.currentLocation;
      if (!(latitude && longitude)) {
        this.modalVisible = true;
      }
    },
    async handleGetCusBarHeight() {
      const height = await this.$refs?.cusBarRef?.handleGetCusBarHeight();
      this.cusBarHeightForPx = height;
      if (height > 0) {
        await this.handleSetPageHeight();
        return;
      }
      await this.handleGetCusBarHeight();
    },
    async handleSetPageHeight() {
      uni.hideLoading();
      const navBarHeight =
        await this.$refs.addressBarRef.handleGetAddressBarHeight();
      const cusBarHeight = this.cusBarHeightForPx;
      this.homePageHeight = `calc(100vh - ${cusBarHeight}px)`;
      // //console.log("获取底部tabbar高度", cusBarHeight);
      this.$nextTick(() => {
        let query = uni.createSelectorQuery().in(this);
        query
          .select(".home-page")
          .boundingClientRect((data) => {
            if (data && data.height > 0) {
              const pageData = Object.assign({}, this.pageData);
              pageData.style.height = data.height - navBarHeight + "px";
              this.pageData = pageData;
              // //console.log(
              //   "首页高度====",
              //   data,
              //   pageData,
              //   navBarHeight,
              //   cusBarHeight
              // );
            }
          })
          .exec();
      });
    },
    handleGetNearbyLocation() {
      const params = {
        latitude:
          this.currentLocation?.latitude || this.location?.latitude || "",
        longitude:
          this.currentLocation?.longitude || this.location?.longitude || "",
      };
      if (!params.latitude && !params.longitude) return;
      uni.request({
        url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${params.latitude},${params.longitude}&key=${TENCENT_MAP_KEY}`,
        success: (res) => {
          console.log("定位数据", res);
          const {
            statusCode,
            data: { status },
          } = res;
          if (statusCode === 200 && status === 0) {
            const {
              data: {
                result: {
                  address,
                  address_reference: { landmark_l2 },
                  location,
                  address_component,
                },
              },
            } = res;
            const params = {
              latitude: location.lat,
              longitude: location.lng,
              address: address || "",
              title: landmark_l2.title,
              distance: landmark_l2._distance,
              address_info: address_component,
            };
            this.$store.dispatch(
              "sp-address/location/setCurrentLocation",
              params
            );
            if (!landmark_l2.title) {
              this.$nextTick(() => {
                this.handleGetNearbyLocation();
              });
            }
          }
        },
      });
    },
    handleOpenLocation() {
      this.modalVisible = false;
      this.$Router.push({
        name: "chooseAddress",
      });
    },
    handleOpenSetting() {
      uni.openSetting();
    },
    handleSearch(e) {
      // //console.log("this.$refs.lcpRef", this.$refs);
      this.$refs.lcpRef.handleSearch(e);
    },
  },
};
</script>

<style lang="scss" scoped>
.home-page {
  width: 100vw;
  font-size: 28rpx;
}
::v-deep.page {
  width: 100% !important;
  height: 100% !important;
}
</style>
